<template>
  <div class="p-6 max-w-6xl mx-auto">
    <h1 class="text-2xl font-bold mb-4">产品维护</h1>

    <div class="mb-4 space-y-2">
      <label class="block">管理员密钥（只在本地保存于浏览器）</label>
      <div class="flex gap-2">
        <input v-model="adminKeyInput" type="password" class="border px-2 py-1 flex-1" placeholder="输入管理员密钥" />
        <button @click="saveKey" class="bg-blue-600 text-white px-3 py-1 rounded">保存并登录</button>
        <button @click="clearKey" class="bg-gray-200 px-3 py-1 rounded">登出</button>
      </div>
      <div v-if="!isAuthenticated" class="text-sm text-red-600">未认证。请输入有效密钥并保存。</div>
    </div>

    <div v-if="isAuthenticated">
      <!-- Create / Edit form -->
      <div class="border rounded p-4 mb-6">
        <h2 class="font-semibold mb-2">{{ editId ? '编辑产品' : '新增产品' }}</h2>
        <div class="grid grid-cols-1 md:grid-cols-2 gap-3">
          <input v-model="form.product_name" placeholder="产品名称" class="border px-2 py-1" />
          <input v-model.number="form.price" type="number" step="0.01" placeholder="价格" class="border px-2 py-1" />
          <input v-model.number="form.quantity" type="number" placeholder="数量" class="border px-2 py-1" />
          <label class="flex items-center gap-2"><input type="checkbox" v-model="form.is_sale" /> 上架</label>
          <textarea v-model="form.product_info" placeholder="产品信息（付款后显示）" class="border px-2 py-1 md:col-span-2"></textarea>
          <textarea v-model="form.detail" placeholder="产品详情" class="border px-2 py-1 md:col-span-2"></textarea>

          <div class="md:col-span-2">
            <label class="block mb-1">图片（可选）</label>
            <input type="file" accept="image/*" @change="onFileChange" />
            <div v-if="imagePreview" class="mt-2">
              <img :src="imagePreview" class="max-h-40 border" />
            </div>
          </div>
        </div>

        <div class="mt-3 flex gap-2">
          <button @click="submit" class="bg-green-600 text-white px-3 py-1 rounded">{{ editId ? '保存' : '创建' }}</button>
          <button @click="resetForm" class="px-3 py-1 border rounded">重置</button>
        </div>
      </div>

      <!-- List -->
      <div class="mb-3 flex items-center gap-2">
        <input v-model="search" @keyup.enter="load" placeholder="搜索产品名称..." class="border px-2 py-1 flex-1" />
        <select v-model.number="pageSize" @change="load" class="border px-2 py-1">
          <option :value="10">10</option>
          <option :value="20">20</option>
          <option :value="50">50</option>
        </select>
        <button @click="load" class="bg-blue-600 text-white px-3 py-1 rounded">刷新</button>
      </div>

      <div v-if="loading" class="py-6 text-center">加载中...</div>
      <div v-if="error" class="text-red-600">{{ error }}</div>

      <div v-if="rows.length" class="overflow-auto border rounded">
        <table class="min-w-full table-auto text-sm">
          <thead class="bg-gray-100">
            <tr>
              <th class="px-3 py-2 text-left">图片</th>
              <th class="px-3 py-2 text-left">名称</th>
              <th class="px-3 py-2 text-left">价格</th>
              <th class="px-3 py-2 text-left">数量</th>
              <th class="px-3 py-2 text-left">上架</th>
              <th class="px-3 py-2 text-left">创建时间</th>
              <th class="px-3 py-2 text-left">操作</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="r in rows" :key="r.id" class="odd:bg-white even:bg-gray-50 align-top">
              <td class="px-3 py-2 align-top"><img v-if="r.image_base64" :src="r.image_base64" class="h-16" /></td>
              <td class="px-3 py-2 align-top">{{ r.product_name }}</td>
              <td class="px-3 py-2 align-top">{{ r.price }}</td>
              <td class="px-3 py-2 align-top">{{ r.quantity }}</td>
              <td class="px-3 py-2 align-top">{{ r.is_sale ? '是' : '否' }}</td>
              <td class="px-3 py-2 align-top">{{ r.creation_time }}</td>
              <td class="px-3 py-2 align-top">
                <button @click="startEdit(r)" class="px-2 py-1 border rounded mr-2">编辑</button>
                <button @click="remove(r.id)" class="px-2 py-1 border rounded bg-red-600 text-white">删除</button>
              </td>
            </tr>
          </tbody>
        </table>
      </div>

      <div class="flex items-center justify-between mt-3">
        <div>第 {{ page }} 页 / 共 {{ totalPages }} 页， 共 {{ total }} 条</div>
        <div class="flex items-center gap-2">
          <button :disabled="page<=1" @click="goto(page-1)" class="px-2 py-1 border rounded">上一页</button>
          <input type="number" v-model.number="gotoPage" class="w-20 px-2 py-1 border" />
          <button @click="goto(gotoPage)" class="px-2 py-1 border rounded">跳转</button>
          <button :disabled="page>=totalPages" @click="goto(page+1)" class="px-2 py-1 border rounded">下一页</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
definePageMeta({ middleware: 'admin-access' })
import { ref, computed, onMounted } from 'vue'

const adminKeyInput = ref('')
const adminKey = ref('')
const isAuthenticated = computed(() => !!adminKey.value)

const form = ref({ product_name: '', price: 0, is_sale: false, quantity: 0, product_info: '', detail: '', image_base64: '' })
const editId = ref('')
const imagePreview = ref('')

const rows = ref([])
const page = ref(1)
const pageSize = ref(20)
const total = ref(0)
const loading = ref(false)
const error = ref('')
const search = ref('')
const gotoPage = ref(1)

const totalPages = computed(() => Math.max(1, Math.ceil(total.value / pageSize.value)))

function saveKey() {
  adminKey.value = adminKeyInput.value
  if (adminKey.value) localStorage.setItem('admin_key', adminKey.value)
  load()
}

function clearKey() {
  adminKeyInput.value = ''
  adminKey.value = ''
  localStorage.removeItem('admin_key')
}

function resetForm() {
  editId.value = ''
  form.value = { product_name: '', price: 0, is_sale: false, quantity: 0, product_info: '', detail: '', image_base64: '' }
  imagePreview.value = ''
}

async function onFileChange(e) {
  const file = (e.target.files && e.target.files[0]) || null
  if (!file) return
  const reader = new FileReader()
  reader.onload = () => {
    const dataUrl = String(reader.result || '')
    // store dataUrl directly (includes mime type)
    form.value.image_base64 = dataUrl
    imagePreview.value = dataUrl
  }
  reader.readAsDataURL(file)
}

async function submit() {
  if (!form.value.product_name) {
    error.value = '请输入产品名称'
    return
  }
  error.value = ''
  try {
  const path = editId.value ? '/api/admin/lin_product.update' : '/api/admin/lin_product.create'
    const payload = { ...form.value }
    if (editId.value) payload.id = editId.value
    const res = await $fetch(path, { method: 'POST', body: payload, headers: { 'x-admin-key': adminKey.value } })
    // reload
    resetForm()
    load()
  } catch (err) {
    error.value = String(err?.message || err)
  }
}

function startEdit(r) {
  editId.value = r.id
  form.value = {
    product_name: r.product_name,
    price: Number(r.price || 0),
    is_sale: Boolean(Number(r.is_sale || 0)),
    quantity: Number(r.quantity || 0),
    product_info: r.product_info || '',
    detail: r.detail || '',
    image_base64: r.image_base64 || ''
  }
  imagePreview.value = r.image_base64 || ''
  window.scrollTo({ top: 0, behavior: 'smooth' })
}

async function remove(id) {
  if (!confirm('确定要删除此产品吗？')) return
  try {
  await $fetch('/api/admin/lin_product.delete', { method: 'POST', body: { id }, headers: { 'x-admin-key': adminKey.value } })
    load()
  } catch (err) {
    error.value = String(err?.message || err)
  }
}

async function load() {
  if (!adminKey.value) return
  loading.value = true
  error.value = ''
  try {
    const res = await $fetch('/api/admin/lin_product', { method: 'GET', headers: { 'x-admin-key': adminKey.value }, params: { page: page.value, pageSize: pageSize.value, search: search.value } })
    if (res && res.data) {
      rows.value = res.data || []
      total.value = res.total || 0
      gotoPage.value = page.value
    }
  } catch (err) {
    error.value = String(err?.message || err)
  } finally {
    loading.value = false
  }
}

function goto(p) {
  const pn = Number(p) || 1
  page.value = Math.min(Math.max(1, pn), totalPages.value)
  load()
}

onMounted(() => {
  try {
    const saved = typeof window !== 'undefined' ? localStorage.getItem('admin_key') : null
    if (saved) {
      adminKeyInput.value = saved
      adminKey.value = saved
      load()
    }
  } catch (e) {}
})

</script>

<style scoped>
img { max-width: 100%; }
</style>
